//
//  ANShopInfoController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/20.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANShopInfoController.h"
#import "ShopInfoTopView.h"
#import "InfoTitleView.h"
#import "ShopInfoEntity.h"
#import "ANSelectMapAlertController.h"
#import "MainGoodsCell.h"
#import "GoodsEntity.h"
#import "FreeItemView.h"
#import "ANGoodsInfoController.h"
#import "ANGoodsListController.h"

@interface ANShopInfoController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) ShopInfoTopView *topView;
@property (nonatomic, strong) InfoTitleView *freeTitleView;
@property (nonatomic, strong) InfoTitleView *goodsTitleView;
@property (nonatomic, strong) InfoTitleView *shopTitleView;
@property (nonatomic, strong) FreeItemView *freeItemView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *shopInfoLab;

@property (nonatomic, strong) ShopInfoTotalEntity *totalEntity;
/** 服务项目列表 */
@property (nonatomic, strong) NSArray<GoodsEntity *> *dataSource;

@end

@implementation ANShopInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"商户详情";
    
    [self requestData];
}

- (void)requestData
{
    NSDictionary *para = @{
                           @"id":self.orgId
                           };
    [URLManager.shareManager getUrlStr:Api_Shop_Detail parameters:para entityClass:[ShopInfoTotalEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                self.totalEntity = baseEntity.data;
                self.topView.entity = self.totalEntity.consuemr;
                self.topView.consumerFileList = self.totalEntity.consumerFileList;
                
                
                NSString *htmlStr = self.totalEntity.consuemr.introduction;
                if (htmlStr == nil || htmlStr.length == 0) {
                    self.shopTitleView.hidden = YES;
                    [self.shopTitleView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.tableView.mas_bottom);
                        make.height.equalTo(@0);
                    }];
                }
                else {
                    [self showShopInfoWithHTMLString:htmlStr];
                }
                if (UserUtils.shared.showVip) {
                    if (self.totalEntity.consuemr.freeItemList && self.totalEntity.consuemr.freeItemList.count > 0) {
                        NSString *filePath = [NSString stringWithFormat:@"%@%@",SERVERADDRS,self.totalEntity.consuemr.freeItemFilePath];
                        [self.freeItemView.icon sd_setImageWithURL:[NSURL URLWithString:filePath] placeholderImage:PlaceHolderImage];
                        NSMutableString *freeString = @"".mutableCopy;
                        for (int i = 0; i < self.totalEntity.consuemr.freeItemList.count; i++) {
                            NSString *subString = self.totalEntity.consuemr.freeItemList[i];
                            [freeString appendString:subString];
                            if (i != self.totalEntity.consuemr.freeItemList.count - 1) {
                                [freeString appendString:@"\n"];
                            }
                        }
                        self.freeItemView.rem = String(freeString);
                    }
                    else {
                        self.freeItemView.hidden = YES;
                        [self.freeItemView mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.freeTitleView.mas_bottom);
                            make.height.equalTo(@0);
                        }];
                        self.freeTitleView.hidden = YES;
                        [self.freeTitleView mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.topView.mas_bottom);
                            make.height.equalTo(@0);
                        }];
                    }
                }
                else {
                    self.freeItemView.hidden = YES;
                    [self.freeItemView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.freeTitleView.mas_bottom);
                        make.height.equalTo(@0);
                    }];
                    self.freeTitleView.hidden = YES;
                    [self.freeTitleView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.topView.mas_bottom);
                        make.height.equalTo(@0);
                    }];
                }
                
                
                [self requestGoods];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

// 查询商户商品
- (void)requestGoods
{
    NSDictionary *body = @{
                           @"consumerId":self.totalEntity.consuemr.orgId,
                           @"pageNo":@"1",
                           @"pageSize":@"2"
                           };
    [URLManager.shareManager getUrlStr:Api_Shop_Trade_List parameters:body entityClass:[GoodsListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                GoodsListEntity *data = baseEntity.data;
                self.dataSource = data.data;
                if (self.dataSource.count > 0) {
                    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.height.equalTo(@(kWidth(100)*data.data.count+(self.dataSource.count>0?30:0)));
                    }];
                    [self.tableView reloadData];
                }
                else {
                    self.goodsTitleView.hidden = YES;
                    [self.goodsTitleView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.height.equalTo(@0);
                        make.top.equalTo(self.freeItemView.mas_bottom);
                    }];
                    self.tableView.hidden = YES;
                    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.goodsTitleView.mas_bottom);
                        make.height.equalTo(@0);
                    }];
                }
                
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

- (void)showShopInfoWithHTMLString:(NSString *)HTMLString
{
    NSData *data = [HTMLString dataUsingEncoding:NSUnicodeStringEncoding];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    self.shopInfoLab.attributedText = attri;
}

// 更多
- (void)moreAction
{
    ANGoodsListController *vc = [[ANGoodsListController alloc] init];
    vc.consumerId = self.totalEntity.consuemr.orgId;
    vc.title = @"更多服务";
    vc.type = ANGoodsListControllerTypeShowMore;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupSubViews
{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    self.topView = [[ShopInfoTopView alloc] init];
    [self.scrollView addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(@(kScreenW));
    }];
    WeakSelf
    self.topView.naviHandler = ^{
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(weakSelf.totalEntity.consuemr.latitude.doubleValue, weakSelf.totalEntity.consuemr.longitude.doubleValue);
        ANSelectMapAlertController *vc = [ANSelectMapAlertController alertWithEndLocation:coordinate endLocationName:weakSelf.totalEntity.consuemr.address];
        [weakSelf presentViewController:vc animated:YES completion:nil];
    };
    self.topView.telHandle = ^{
        NSString *tel = weakSelf.totalEntity.consuemr.telephone;
        UIWebView *callWebView = [[UIWebView alloc] init];
        NSURL *telURL          = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",tel]];
        [callWebView loadRequest:[NSURLRequest requestWithURL:telURL]];
        [weakSelf.view  addSubview:callWebView];
    };
    
    self.freeTitleView = [[InfoTitleView alloc] init];
    self.freeTitleView.titleLab.text = @"会员免费服务项目";
    [self.scrollView addSubview:self.freeTitleView];
    [self.freeTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom).offset(kWidth(40));
        make.left.right.equalTo(self.scrollView);
    }];
    
    self.freeItemView = [[FreeItemView alloc] init];
    [self.scrollView addSubview:self.freeItemView];
    [self.freeItemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.scrollView);
        make.top.equalTo(self.freeTitleView.mas_bottom).offset(kWidth(10));
    }];
    
    self.goodsTitleView = [[InfoTitleView alloc] init];
    self.goodsTitleView.titleLab.text = @"商家推荐";
    [self.scrollView addSubview:self.goodsTitleView];
    [self.goodsTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.freeItemView.mas_bottom).offset(kWidth(40));
//        make.top.equalTo(self.freeTitleView.mas_bottom).offset(kWidth(20)).priority(200);
        make.left.right.equalTo(self.scrollView);
    }];
    
    [self.scrollView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.goodsTitleView.mas_bottom).offset(kWidth(10));
        make.right.left.equalTo(self.scrollView);
    }];
    [self.tableView registerClass:[MainGoodsCell class] forCellReuseIdentifier:@"神奇的cell"];
    
    self.shopTitleView = [[InfoTitleView alloc] init];
    self.shopTitleView.titleLab.text = @"商家信息";
    [self.scrollView addSubview:self.shopTitleView];
    [self.shopTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom).offset(kWidth(40));
        make.left.right.equalTo(self.scrollView);
    }];
    
    self.shopInfoLab = [[UILabel alloc] init];
    self.shopInfoLab.backgroundColor = [UIColor whiteColor];
    self.shopInfoLab.numberOfLines = 0;
    [self.scrollView addSubview:self.shopInfoLab];
    [self.shopInfoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shopTitleView.mas_bottom).offset(kWidth(10));
        make.left.right.equalTo(self.scrollView);
        make.bottom.equalTo(self.scrollView);
    }];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"神奇的cell" forIndexPath:indexPath];
    cell.showShopName = NO;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.entity = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ANGoodsInfoController *vc = [[ANGoodsInfoController alloc] init];
    vc.goodsEntity = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kWidth(100);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (self.dataSource.count) {
        UILabel *footer = [[UILabel alloc] init];
        footer.textColor = kColor666666;
        footer.font = [UIFont systemFontOfSize:13];
        footer.text = @"更多 >";
        footer.textAlignment = NSTextAlignmentCenter;
        footer.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreAction)];
        [footer addGestureRecognizer:tap];
        return footer;
    }
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.dataSource.count>0) {
        return 30;
    }
    return 0.01;
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.scrollEnabled = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
